﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using VacationDaysCommons;
using VacationDaysDatabase;
using VacationDaysCommons.Faults;
using System.ServiceModel;

namespace VacationDaysClient
{
    /// <summary>
    /// Interaction logic for RegisterUser.xaml
    /// </summary>
    public partial class RegisterUser : Window
    {
        private bool registerMode = false;
        private VDEmployee existingUser;

        public RegisterUser()
        {
            registerMode = true;
            InitializeComponent();
            newUserControls.Visibility = registerMode ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            updateUserControls.Visibility = registerMode ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
            newUserlabel.Visibility = registerMode ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            usernamePanel.Visibility = registerMode ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            passwordPanel.Visibility = registerMode ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            emailPanel.Visibility = registerMode ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            PMBox.Visibility = registerMode ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
            this.Height = 490;
        }

        public RegisterUser(VDEmployee existingEmployee)
        {
            existingUser = existingEmployee;

            registerMode = false;
            
            InitializeComponent();
            email.Text = existingUser.Email;
            email.IsEnabled = registerMode;
            password.Text = existingUser.Password;
            password.IsEnabled = registerMode;
            username.Text = existingUser.UserName;
            username.IsEnabled = registerMode;
            firstname.Text = existingUser.FirstName;
            lastname.Text = existingUser.LastName;
            userRole.SelectedIndex = (int)existingUser.Role;
            PMSelection.SelectedPM = new VDEmployee() { Id = existingUser.PM } ;
            newUserControls.Visibility = registerMode ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            updateUserControls.Visibility = registerMode ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
            newUserlabel.Visibility = registerMode ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            usernamePanel.Visibility = registerMode ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            passwordPanel.Visibility = registerMode ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            emailPanel.Visibility = registerMode ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            PMBox.Visibility = registerMode ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
            this.Height = 290;
        }


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (username.Text == "")
            {
                var tt = new ToolTip();
                SetValidationError(username, "Username required");
                return;
            }
            if (password.Text == "")
            {
                SetValidationError(password, "Password required");
                return;
            }
            if (email.Text == "")
            {
                SetValidationError(email, "Email required");
                return;
            }
            if (!email.Text.Contains('@') || !email.Text.Contains('.'))
            {
               SetValidationError(email, "Email address invalid. Should be \"user@server.ext\"");
               return;
            }

            GoRegisterUser(username.Text, password.Text, lastname.Text, firstname.Text, email.Text, (EmployeeRole)userRole.SelectedIndex, loginOnSuccess.IsChecked);
        }

        private void GoRegisterUser(string UserName, string UserPass, string UserLastName, string UserFirstName, string UserEmail, EmployeeRole UserRole, bool? loginIfSuccess )
        {
            
            // create this with empty User ID. if server validates it, it will fill in the guid
            var newUserInfo = new VDEmployee() {Id = Guid.Empty, Email = UserEmail, FirstName = UserFirstName, LastName = UserLastName, Password = UserPass, UserName = UserName, Role = UserRole};

            using (VDUserServiceClient vu = new VDUserServiceClient())
            {
                try
                {
                    var createdUser = vu.CreateNewUser(newUserInfo);
                    if (loginIfSuccess.GetValueOrDefault(false))
                    {
                        Application.Current.MainWindow = new UserWindow(createdUser);
                        Application.Current.MainWindow.Show();
                        Close();
                    }
                }
                catch (FaultException<VDUsernameAlreadyExistsFault>)
                {
                    SetValidationError(username, "User name is already in use!");
                    return;
                }
                catch (FaultException<VDEmailAlreadyExistsFault>)
                {
                    SetValidationError(email, "Email address is already in use!");
                    return;
                }
                catch (FaultException)
                {
                    MessageBox.Show("An unknown error occured while creating user.\nPLease try again!");
                    return;
                }
            }
        }

        private void GoUpdateUser(string UserLastName, string UserFirstName, EmployeeRole UserRole, Guid PMId)
        {
            var updatedUserInfo = new VDEmployee() { Id = existingUser.Id, FirstName = UserFirstName, LastName = UserLastName, Role = UserRole, PM = PMId };
            using (VDUserServiceClient vu = new VDUserServiceClient())
            {
                bool success = vu.UpdateUser(updatedUserInfo);

                if (success)
                {
                    DialogResult = true;
                    Close();
                }
                else
                {
                    MessageBox.Show("There was an error updating the user data!");
                }
            }
        }

        private void SetValidationError(Control uiElement, string errortext)
        {
            //var tt = new ToolTip();
            //tt.Content = errortext;
            //tt.IsOpen = true;
            //uiElement.ToolTip = tt;
            //tt.PlacementTarget = uiElement;
            //tt.Placement = System.Windows.Controls.Primitives.PlacementMode.Top;
            MessageBox.Show(string.Format("{0}", errortext), "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            uiElement.Focus();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            email.Text = "";
            password.Text = "";
            username.Text = "";
            firstname.Text = "";
            lastname.Text = "";
            userRole.SelectedIndex = 0;
            username.Focus();
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            GoUpdateUser(lastname.Text, firstname.Text, (EmployeeRole)userRole.SelectedIndex, PMSelection.SelectedPM.Id);
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        private void button2_Click_1(object sender, RoutedEventArgs e)
        {

        }
    }
}
